##Get objects
old_ws = ls()

#################
#Tables Security#
#################

useTable_security = mergedTable_podes[!is.na(pct_security_new_any) & (sample_ni_it)]

#Make index
###########
security_vars = paste0('pct_security_new', c('_guard', '_post', '_civil_defense'))

#Create Index for NI vs IT Sample
for (v in security_vars){
  #Index of randomized group
  r_idx = useTable_security[, (sample_ni_it) %>% which] 
  #Index of control group
  c_idx = useTable_security[, (!(ICIT_win) & (sample_ni_it)) %>% which] 
  #Mean and SD of control group
  c_mu = useTable_security[[v]][c_idx] %>% mean
  c_sigma = useTable_security[[v]][c_idx] %>% sd
  #Index component = z score using control group mean and SD
  set(useTable_security, 
      i = r_idx, 
      j = paste0('idx_it_', v),
      value = (useTable_security[[v]][r_idx] - c_mu) / c_sigma
  )
}
#Create index by taking mean of all components
useTable_security[, security_index_it := rowMeans(.SD), .SDcols = paste0('idx_it_', security_vars)]

################
#Specifications#
################
lm_specs = expand.grid(x = 'IT_win', 
                       y = c(security_vars, 'security_index_it'),
                       stringsAsFactors = F
)

#Descriptives
Map(function(y) summ_loop(y, useTable_security),
    c(lm_specs$y)) %>% 
  rbindlist %>%
  fwrite("./output/descriptives/security.csv")


#Estimate model
lm_models = Map(function(y,x) lm_loop(y,x, useTable_security),
                lm_specs$y, lm_specs$x)

#Make standard errors
table_list = c(lm_models)
table_se = lapply(table_list, function(x) cluster_errors(x, useTable_security[, cluster]) %>% diag %>% sqrt)

#Make table note
n_clusters = useTable_security$cluster %>% unique %>% length
note_text = paste("Standard errors clustered by", n_clusters, "constituency clusters.
                   Observations are constituencies in which the last seat was contested by Islamist 
                   and secular nationalist parties with a margin less than 1 percent.")

#Make table
table = stargazer(table_list, se = table_se, type = 'latex', 
          title = "Estimated Effects of Islamist Victory on Local Security Measures",
          #out = './output/tables/security_ni_it.tex',
          label = 'tab:security_ni_it',
          model.names = F,
          model.numbers = F,
          dep.var.labels = c("Security Guard", 'Security Post', 'Civil Defense', 'Security Index'), 
          dep.var.caption = "",
          covariate.labels = c("Islamist Win"),
          star.cutoffs = c(0.1, 0.05, 0.01),
          #float.env = 'sidewaystable',
          notes.align = 'l',
          keep.stat = 'n',
          style = 'apsr')

write_latex(table, note_text, './output/tables/table_e2.tex')

#Clean up
drop = setdiff(ls(), c(old_ws)) 
rm(list = drop)